import { computed } from 'vue';
import moment from 'moment'
import { lastDayOfYear, lastDayOfMonth, lastDayOfWeek, dayTimeEnd, formatDate, getTimestamp } from 'pub-bbx-utils';
import { t } from '@src/locales';



export type DatePeriodType = 'date' | 'month' | 'year' | 'week';

export type DatePeriodValue = {
  startTime: moment.MomentInput;
  endTime: moment.MomentInput;
  type: DatePeriodType;
};

export const datePeriodProps = {
  isHideDate: {
    type: Boolean,
    default: false,
  },
  isHideWeek: {
    type: Boolean,
    default: false,
  },
  isHideMonth: {
    type: Boolean,
    default: false,
  },
  isHideQuarter: {
    type: Boolean,
    default: false,
  },
  isHideYear: {
    type: Boolean,
    default: false,
  },
  isSelectChangeNotEmit: {
    type: Boolean,
    default: false,
  },
  value: {
    type: Object,
    default: null,
  },
  range: {
    type: Boolean,
    default: false,
  },
  valueFormat: {
    type: String,
    default: 'YYYY-MM-DD',
  },
};

type DateTypeOption = {
  label: string;
  value: DatePeriodType;
  isShow: boolean;
};

export const useOptions = (props: typeof datePeriodProps) => {
  return computed(() => {
    const options: Array<DateTypeOption> = [
      { value: 'date', label: t('common.time.day'), isShow: !props.isHideDate },
      { value: 'week', label: t('common.time.week'), isShow: !props.isHideWeek },
      { value: 'month', label: t('common.time.month'), isShow: !props.isHideMonth },
      { value: 'year', label: t('common.time.year'), isShow: !props.isHideYear },
    ];
    return options.filter(option => option.isShow);
  });
};

// element-ui的日期选择器的格式
export const formatMap = (): Record<DatePeriodType, string> => ({
  date: 'yyyy-MM-dd',
  month: 'yyyy-MM',
  year: 'yyyy',
  week: `yyyy WW ${t('common.time.week')}`,
});

type DateOfType = (date: moment.MomentInput) => Date;

const lastDateOfType: Record<DatePeriodType, DateOfType> = {
  week: (date: moment.MomentInput) => lastDayOfWeek(date),
  month: (date: moment.MomentInput) => lastDayOfMonth(date),
  year: (date: moment.MomentInput) => lastDayOfYear(date),
  date: (date: moment.MomentInput) => dayTimeEnd(date),
};

export const endTimeOfType = (date: moment.MomentInput, type: DatePeriodType) => {
  return lastDateOfType[type](date);
};

// 转换成Date
export function transToDate(value: moment.MomentInput) {
  if (value) {
    return moment(value).toDate();
  }
  return null;
}

// 格式化选中结果
export function formatValue(date: moment.MomentInput, format = 'YYYY-MM-DD', defaultTime?:string) {
  // 获取时间戳
  const timestamp = getTimestamp(date, defaultTime)!;
  // 返回数据格式
  return format === 'timestamp' || format === 'x' ? timestamp : formatDate(timestamp, format);
}

export const useDate = () => {
  return {
    endTimeOfType,
    transToDate,
    formatValue,
  };
};
